 <template>
  <div>
    <div class="filter-container">
      <el-autocomplete
        v-model="searchEnterpriceData"
        @keyup.enter.native="keyPress"
        :fetch-suggestions="querySearchAsync"
        placeholder="请输入企业名称"
        @select="handleSelect"
      ></el-autocomplete>
      <el-input placeholder="姓名/电话" v-model="searchData" style="width: 200px;" class="filter-item"/>

      <el-button
        class="filter-item add-style"
        icon="el-icon-search"
        type="primary"
        @click="search"
      >搜索</el-button>
    </div>

    <tTable :columns="columns" :data="tableData">
      <!-- 余额 -->
      <template v-slot:balance="slotProps">
        <span>￥{{slotProps.scope.row.balance}}</span>
      </template>

      <!-- 操作 -->
      <template v-slot:operate="slotProps">
        <el-button @click="checkDetail(slotProps.scope.row.userAccountId)" size="mini">课程购买情况</el-button>
        <el-button
          type="primary"
          class="add-style"
          @click="showEnterpriseDialog(slotProps.scope.row.endUserId, slotProps.scope.row.inviteCode)"
          size="mini"
        >修改所属企业</el-button>
        <el-button
          @click="addFreeCourse(slotProps.scope.row.userAccountId)"
          type="warning"
          class="edit-style"
          size="mini"
        >添加试用课程</el-button>
      </template>
    </tTable>

    <Pagination :total="total" @handleChange="handleChange"/>

    <!-- 修改所属企业 -->
    <el-dialog title="所属机构" :visible.sync="enterpriseDialogVisible" width="60%">
      <div>
        <div>
          <el-form label-width="200px">
            <el-form-item label="机构码">
              <el-input
                @keyup.enter.native="searchEnterprise"
                style="width:300px;"
                type="text"
                v-model="currentCode"
              >
                <el-button @click="searchEnterprise" slot="append" icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
            <el-form-item label="机构">
              <div>{{currentEnterprise}}</div>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="text" @click="enterpriseDialogVisible = false">取消</el-button>
        <el-button type="primary" class="add-style" @click="updateCode">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="已购课程" :visible.sync="dialogVisible" width="60%">
      <div>
        <tTable :columns="courseColumns" :data="courseList">
          <!-- 操作 -->
          <template v-slot:courseBrief="slotProps">
            <div class="course-des">{{slotProps.scope.row.courseBrief}}</div>
          </template>
        </tTable>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" class="add-style" @click="dialogVisible = false">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="添加试用课程" :visible.sync="temporaryDialogVisible" width="60%">
      <div>
        <!-- <div>添加使用时长</div> -->
        <el-form label-width="100px">
          <el-form-item>
            <label for style="margin-right: 10px;">时间</label>
            <el-radio-group v-model="timeDuration">
              <el-radio
                v-for="item in timeGroup"
                :key="item.duration"
                :label="item.duration"
              >{{item.name}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <label for style="margin-right: 10px;">课程</label>
            <el-radio-group v-model="courseId">
              <el-radio v-for="item in courseGroup" :key="item.id" :label="item.id">{{item.name}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="temporaryDialogVisible = false">取消</el-button>
        <el-button type="primary" class="add-style" @click="addTime">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { selectOrganization } from "api/getData";
import {
  getAllInviteUser,
  getUserCourse,
  getAllInviteUserById,
  selectEnterpriseByCode,
  updateCode
} from "api/user";
import { getOrganization } from "api/getData";
import { getCourse, addCourseTime } from "api/course";
import { formatDateTime } from "src/util/time.js";
import { baseUrl } from "src/config/env.js";

import Pagination from "src/components/pagination";
import tTable from "src/components/table/index.vue";

export default {
  data() {
    return {
      tableData: [],
      courseList: [], //用户已购买课程列表
      searchData: "",
      dialogVisible: false,
      isSearch: false,
      temporaryDialogVisible: false, // 试用课程的dialog
      orgIndex: "", // 当前选择的企业
      orgList: [], // 企业列表

      timeGroup: [
        { name: "一个月", duration: 1 },
        { name: "三个月", duration: 3 },
        { name: "六个月", duration: 6 },
        { name: "一年", duration: 12 },
        { name: "两年", duration: 24 }
      ],
      courseGroup: [],
      timeDuration: 1, // 当前选择的时长
      courseId: -1, // 当前选择的课程id

      currentUserId: "", //当前选择的用户id
      orgId: "", // 当前选择的企业id
      currentCode: "", // 当前修改的企业code
      currentEnterprise: "", // 当前的企业名称
      total: -1,

      searchEnterpriceData: "", // 企业搜索
      enterpriseDialogVisible: false, // 修改所属企业的标识

      enterprises: [],
      state: "",
      timeout: null,

      // 用户
      columns: [
        {
          attr: { label: "", type: "index", width: "50" }
        },
        {
          attr: { prop: "name", label: "姓名" }
        },
        {
          attr: { prop: "phone", label: "电话", width: "120" }
        },
        {
          slot: "balance",
          attr: { prop: "balance", label: "余额", width: "80" }
        },
        {
          attr: { prop: "inviteCode", label: "机构码", width: "90" }
        },
        {
          attr: { prop: "inviteName", label: "邀请人" }
        },
        {
          attr: { prop: "createTime", label: "注册时间", width: "160" }
        },
        {
          slot: "operate",
          attr: { label: "操作", width: "400" }
        }
      ],
      // 课程购买情况
      courseColumns: [
        {
          attr: { label: "", type: "index", width: "50" }
        },
        {
          attr: { prop: "courseName", label: "名称" }
        },
        {
          slot: "courseBrief",
          attr: { prop: "courseBrief", label: "课程描述" }
        },
        {
          attr: { prop: "effectiveTime", label: "起始时间" }
        },
        {
          attr: { prop: "endTime", label: "到期日" }
        }
      ]
    };
  },
  mounted() {
    this.getData(1);
    this.getAllOrg();
  },
  watch: {
    searchEnterpriceData: {
      handler: function(newVal, oldVal) {
        if (newVal === "") {
          this.selectId = "";
          this.getData(1);
        } else {
          selectOrganization(newVal).then(res => {
            this.enterprises = res.content.map(item => {
              item.value = item.infoName;
              return item;
            });
          });
        }
      }
    }
  },
  components: { Pagination, tTable },
  methods: {
    // -----------------企业搜索--------------------
    querySearchAsync(queryString, cb) {
      var enterprises = this.enterprises;
      var results = queryString
        ? enterprises.filter(this.createStateFilter(queryString))
        : enterprises;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 3000 * Math.random());
    },
    createStateFilter(queryString) {
      return state => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    handleSelect(item) {
      this.selectId = item.id;
      getAllInviteUserById(item.id).then(res => {
        this.total = res.totalElements;
        this.tableData = res.content.map(item => {
          item.createTime = formatDateTime(item.createTime);
          return item;
        });
      });
    },
    // -----------------企业搜索--------------------

    // ---------------修改所属机构--------------
    showEnterpriseDialog: function(id, code) {
      this.currentUserId = id;
      this.enterpriseDialogVisible = true;
      this.currentCode = code;
      this.searchEnterprise();
    },
    searchEnterprise: function() {
      if (!this.currentCode) return;
      selectEnterpriseByCode(this.currentCode).then(res => {
        this.currentEnterprise = res.infoName;
        this.orgId = res.id;
      });
    },
    updateCode: function() {
      if (!this.orgId) {
        this.$message.error("请选择企业");
        return;
      }
      updateCode(this.currentUserId, this.orgId).then(res => {
        this.$message.success("修改成功");
        this.enterpriseDialogVisible = false;
        this.getData(1);
      });
    },
    // ---------------修改所属机构--------------
    deleteRow: function(index, data) {},
    search: function() {
      this.getData(1, this.searchData);
      this.isSearch = true;
    },
    handleCreate: function() {},
    getData(pageNumber, searchData, orgId) {
      getAllInviteUser(pageNumber, this.searchData, this.selectId).then(res => {
        this.total = res.totalElements;
        this.tableData = res.content.map(item => {
          item.createTime = formatDateTime(item.createTime);
          return item;
        });
      });
    },
    changeOrg: function() {},
    // 获取所有企业
    getAllOrg(pageNumber) {
      getOrganization(pageNumber).then(res => {
        this.orgList = res;
        this.getData(); // 进入页面后才能获取课程id，再根据课程id查询内测用户
      });
    },
    // 修改选择的时间
    changeTime() {},
    checkDetail(id) {
      this.dialogVisible = true;
      getUserCourse(id).then(res => {
        this.courseList = res.map(item => {
          item.endTime = formatDateTime(item.endTime);
          item.effectiveTime = formatDateTime(item.effectiveTime);
          item.courseCover = baseUrl + "/" + item.courseCover;
          return item;
        });
      });
    },
    // 点击分页
    handleChange: function(pageNumber) {
      if (this.isSearch || this.selectId) {
        this.getData(pageNumber, this.searchData, this.selectId);
        // } else if (this.isSearch) {
        //   this.getData(pageNumber, this.searchData);
        // } else if (this.selectId) {
        //   this.getData(pageNumber, this.searchData, this.selectId);
      } else {
        this.getData(pageNumber);
      }
    },
    addFreeCourse: function(id) {
      this.temporaryDialogVisible = true;
      this.currentUserId = id;

      getCourse().then(res => {
        this.courseGroup = res;
        this.courseId = res[0].id;
      });
    },
    // 添加免费时长
    addTime() {
      var userId = this.currentUserId;
      var duration = this.timeDuration;
      var courseId = this.courseId;
      this.temporaryDialogVisible = false;

      addCourseTime(userId, courseId, duration).then(res => {
        this.$message.success("添加成功");
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "src/style/mixin";
.filter-container {
  margin: 15px 0;
}

.course-des {
  width: 180px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>
